<?php

namespace App\Server;

use App\Model\AccessToken;
use Carbon\Carbon;
use GuzzleHttp\Client;

class Wechat
{
    public $config;

    public function __construct()
    {
        $this->config = [
            'appid' => 'wx7fc1ef73941f5f9f',//小程序 appId
            'secret' => '77fb98a158198338306c813b74d01e20'//小程序 appSecret
        ];
    }

    public function getAccessToken()
    {
        $accessToken = AccessToken::active();
        if ($accessToken && $accessToken->access_token) {
            return $accessToken->access_token;
        }

        $config = $this->config;
        $url = 'https://api.weixin.qq.com/cgi-bin/token?appid=' . ($config['appid'] ?? '') . '&secret=' . ($config['secret'] ?? '') . '&grant_type=client_credential';
//        $option = [
//            'appid' => $config['appid'] ?? '',
//            'secret' => $config['secret'] ?? '',
//            'grant_type' => 'client_credential',//固定参数
//        ];
        $client = new Client(['verify' => false]);
        $result = $client->request('get', $url);
        $result = json_decode($result->getBody()->getContents(), true);
        if (!($result['access_token'] ?? '')) {
            return '';
        }

        $accessToken = new AccessToken();
        $accessToken->access_token = $result['access_token'];
        $accessToken->expiration_time = Carbon::parse(date('Y-m-d H:i:s'))->addSeconds(7000);
        $accessToken->save();
        return $result['access_token'] ?? '';
    }

    /**
     * 微信小程序登录(获取用户的openid)
     * @param $jsCode
     * @return mixed|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function code2Session($jsCode)
    {
        //$jsCode:前端登录时获取的 code，可通过wx.login获取
        $config = $this->config;
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . ($config['appid'] ?? '') . '&secret=' . ($config['secret'] ?? '') . '&grant_type=authorization_code&js_code=' . $jsCode;
        $client = new Client(['verify' => false]);
        $result = $client->request('get', $url);
        $result = json_decode($result->getBody()->getContents(), true);

        return $result['openid'] ?? '';
    }

    /**
     * 获取用户手机号
     * @param $jsCode
     * @return mixed|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getPhoneNumber($jsCode)
    {
        //$jsCode:前端获取的 code，可通getPhoneNumber按钮获取
        $token = $this->getAccessToken();
        if (!$token) {
            return '';
        }

        $option = [
            'json' => [
                'code' => $jsCode,
            ]
        ];

        $config = $this->config;
        $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $token;
        $client = new Client(['verify' => false]);
        $result = $client->request('post', $url, $option);
        $result = json_decode($result->getBody()->getContents(), true);

        return $result['phone_info']['purePhoneNumber'] ?? '';
    }
}
